package cn.jsu.oj.dispatchServer.satellite.netty;

import cn.jsu.oj.dispatchServer.satellite.config.ResourceConfig;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * netty服务配置
 *
 * @author shan
 * @date 2022/07/07
 */
@Slf4j
@Component("nettyService")
@DependsOn("clientConfig")
public class NettyService {

    @Autowired
    Bootstrap bootstrap;

    private static final String IP = ResourceConfig.getConfigString("client-active-server-ip");

    private static final Integer PORT = ResourceConfig.getConfigInteger("client-active-server-port");

    public void init() {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Objects.requireNonNull(this.bootstrap, "----------引导器配置失败......")
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler((ChannelHandler) SpringUtil
                        .getBean("nettyChannel"));
        log.info("----------通道处理节点配置完成......");
    }

    public void start() {
        ChannelFuture channelFuture = bootstrap.connect(IP, PORT);
        if (!channelFuture.isSuccess()) {
            return;
        }
        try {
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
